/**
 * @author Kostya
 */

var viewport = null;

var iSessionWinReference = null;
var iReminderWinReference = null;
var iEventCaption = '';
var iEventDates = '';
var iEventRecInfo = '';
var iNotification = '';

var iMainWin = null;

var iMainToolbar = null;

var iSessionButton = null;

var iSettingsButton = null;
var iPasteButton = null;

var iSessionMenu = null;

var iSessionRecord = null;
var iToken = null;

var iOnline = false;

var iUserDateFormat = 'd/m/y';

var iAgendaStore = null;
var iDaysField = null;
var iRefreshButton = null;
var iAgendaGrid = null;
var iTagsToolbar = null;
var iSaveButton = null;

var iEditorsPanel = null;
var iTaskField = null;
var iDDPanel = null;

var iUpdateTimeoutID = -1;
var iEventReminderIDs = [];
var iEventIDs = [];

var showNotification = function(aMessage){
	iNotification = aMessage;
	openNewWindow(generateRandomString(5), 'notify.html', null, 'none', true);
}

var iNetworkListener = function(aNetwork){
	refreshUI(aNetwork);
}

var refreshUI = function(aNetwork){
	if(!iOnline)
		iStatusBarCaption = 'Not connected';
	iSessionButton.setDisabled(aNetwork);
	iSettingsButton.setDisabled(aNetwork || !iOnline);
	iPasteButton.setDisabled(aNetwork || !iOnline);
	iRefreshButton.setDisabled(aNetwork || !iOnline);
	iTagsToolbar.setDisabled(aNetwork || !iOnline);
	iSaveButton.setDisabled(aNetwork || !iOnline);
	iEditorsPanel.setVisible(iOnline);
	iTaskField.setDisabled(aNetwork);
	viewport.doLayout();
}

var openNewSessionWindow = function(){
	return openNewWindow('newSession', 'new_session.html');
}

Ext.state.Manager.setProvider(new Ext.air.FileProvider({
	file: 'beorganized.state',
	defaultState : {
		mainWindow : {
			width:280,
			height:500
		},
		newSession : {
			width:360,
			height:192
		},
		passwordWin : {
			width:280,
			height:145
		},
		settingsWin : {
			width:400,
			height:450
		},
		selectNote : {
			width:350,
			height:300
		},
		reminderWin : {
			width:300,
			height:150
		}
	}
}));

var verifyToken = function(){
	callAPI(iSessionRecord.get('server'), 'user.GetCurrentUser', {
		token: iToken
	}, function(aXML){
//		air.trace('everything is ok, working');
		iStatusBarCaption = iSessionRecord.get('login')+'@'+iSessionRecord.get('server');
//		iUserDateFormat = aXML.documentElement.getAttribute('dateFormat');
		iStatusBar.setText(iStatusBarCaption);
		showNotification('Session <i>'+iStatusBarCaption+'</i> has been opened');
		iOnline = true;
		refreshUI(false);
		refreshAgenda(true);
	}, function(aError){
		iToken = null;
		askForPassword();
	})
}

var ISODateToFlexDate = function(aISODate){
	aISODate = aISODate.replace(/-/g, '/');
	aISODate = aISODate.replace('T', ' ');
//	air.trace('now date is: '+aISODate);
	return new window.runtime.Date(window.runtime.Date.parse(aISODate));
}

var askForPassword = function(){
	return openNewWindow('passwordWin', 'password.html');
}

var afterAskPassword = function(aToken, aSavePassword){
	if(aSavePassword && iSessionRecord){
		iSessionRecord.set('token', aToken);
		iSessionRecord.set('save_pass', true);
		sessions.save();
	}
	iToken = aToken;
	verifyToken();	
}

var ELEMENTS_TO_SKIP = 1;

var showAgendaReminder = function(){
	if(iEventIDs.length==0)
		return;
	var lEventID = iEventIDs[0];
	iEventIDs.splice(0, 1);
	iAgendaStore.each(function(record){
		if(record.get('id')==lEventID){
			iEventCaption = record.get('name');
			iEventDates = record.get('dates');
			iEventRecInfo = record.get('recInfo');
			if(!openNewWindow('reminderWin', 'reminder.html', 'utility'))
				iReminderWinReference.updateCaption();
			return false;
		}
	});
}

var refreshAgenda = function(aFullLoad){
//	showNotification('Refresh agenda');
	clearTimeout(iUpdateTimeoutID);
	for(var i = 0; i<iEventReminderIDs.length; i++){
		clearTimeout(iEventReminderIDs[i]);
	}
	iEventReminderIDs = [];
	iEventIDs = [];
	var tagsString = '';
	if(aFullLoad){
		//Move to read response!!!
	}else{
		//Check all tag buttons
		for(var i = ELEMENTS_TO_SKIP; i < iTagsToolbar.items.getCount();i++){
			var item = iTagsToolbar.items.itemAt(i);
			if(item.pressed){
				if(tagsString!='')
					tagsString += ',';
				tagsString += item.tagText;
			}
		}
		
	}
	
	//Clear tags
	
	var daysBetween = iSessionRecord.get('next_days')?iSessionRecord.get('next_days'):2;
	
	if(daysBetween<0)
		daysBetween = 0;
	var lXMLString = null;
	if(tagsString!=''){
		var lXML = document.implementation.createDocument("","",null);
		var lFilter = lXML.createElement('filter');
		lXML.appendChild(lFilter);
		lFilter.setAttribute('tagsfilter', tagsString);
		var serializer = new XMLSerializer();
		lXMLString = serializer.serializeToString(lXML);
	}
	callAPI(iSessionRecord.get('server'), 'agenda.GetAgenda', {
		noteid: iSessionRecord.get('agenda_id'),
		appendpaths: 'true',
		addtags: 'true',
		calendar: 'false',
		token: iToken,
//		object:{
//			filter:{
//				tagsfilter: tagsString
//			}
//		},
		nextdays: daysBetween
	}, function(aXML){
		iAgendaStore.removeAll();
		var tags = [];
		var events = [];
		for(var i = 0; i<aXML.documentElement.childNodes.length; i++){
			var obj = aXML.documentElement.childNodes[i];
			if(obj.nodeType!=1)
				continue;
			if(obj.nodeName=='tag'){
				tags[tags.length] = obj.getAttribute('name');
				continue;
			}
			var crumb = '';
			for(var j = 0; j<obj.childNodes.length; j++){
				var p = obj.childNodes[j];
				if(p.nodeType!=1)
					continue;
				if(j>0)
					crumb += ' &gt; ';
				crumb += '<span class="crumb">'+escapeHTML(p.getAttribute('text'))+'</span>';
			}
			if(''==crumb)
				crumb = '&nbsp;';
			if(obj.getAttribute('type')!='3' && obj.getAttribute('endDate') && iSessionRecord.get('show_reminder')){
				try{
					var lStartDate = ISODateToFlexDate(obj.getAttribute('startDate'));
					var lNow = new window.runtime.Date();
					var lMinutesBebore = parseInt(iSessionRecord.get('show_reminder_before'))<1?
							1:parseInt(iSessionRecord.get('show_reminder_before'));
					var lTimer = lStartDate.time-lNow.time-lMinutesBebore*1000*60;
					if(lTimer>0){
//						air.trace('ms: '+lTimer+', mins: '+lTimer/1000/60);
						iEventIDs[iEventIDs.length] = obj.getAttribute('id');
						iEventReminderIDs[iEventReminderIDs.length] = setTimeout(function(){
//							air.trace('timer!');
							showAgendaReminder();
						}, Math.floor(lTimer));
					}
				}catch(error){
					
				}
			}
			iAgendaStore.add(new Ext.data.Record({
				id: obj.getAttribute('id'),
				selectable: obj.getAttribute('type')=='3',
				name: obj.getAttribute('text'),
				crumb: crumb,
				icon: obj.getAttribute('icon'),
				add_icon: obj.getAttribute('add_icon'),
				urgent: obj.getAttribute('urgent'),
				recInfo: obj.getAttribute('recurrenceInfo'),
				dates: obj.getAttribute('dates')
			}));
		}
		if(aFullLoad){
			for(var i = ELEMENTS_TO_SKIP; i < iTagsToolbar.items.getCount();){
				var item = iTagsToolbar.items.itemAt(i);
				iTagsToolbar.items.removeAt(i);
				item.destroy();
			}			
		}
		if(aFullLoad && tags.length>0){
			//Create tag buttons
//			agendaToolbar.add('-', 'Tags:');
			for(var i = 0; i< tags.length; i++){
				var lTagButton = new Ext.Toolbar.Button({
					text: escapeHTML(tags[i]),
					iconCls: 'tag',
					enableToggle: true,
					handler: function(){
						refreshAgenda(false);
					}
				});
				lTagButton.tagText = tags[i];
				iTagsToolbar.add(lTagButton);
			}
		}
		if(iTagsToolbar.items.getCount()>ELEMENTS_TO_SKIP)
			iTagsToolbar.setVisible(true);
		else
			iTagsToolbar.setVisible(false);
		iAgendaGrid.syncSize();
		viewport.doLayout();
		iAgendaGrid.getView().focusRow(0);
//		air.trace('setting timeout to '+(parseInt(iSessionRecord.get('update_interval'))*1000*3));
		iUpdateTimeoutID = setTimeout(function(){
			refreshAgenda(false)
		}, parseInt(iSessionRecord.get('update_interval'))*1000*60);//!!!
	}, function(){}, lXMLString);
}

var loadSession = function(aSessionID, aToken){
	//Disable everything!
	clearTimeout(iUpdateTimeoutID);
	for(var i = 0; i<iEventReminderIDs.length; i++){
		clearTimeout(iEventReminderIDs[i]);
	}
	iEventReminderIDs = [];
	iOnline = false;
	iStatusBarCaption = 'Not connected';
	iStatusBar.setText(iStatusBarCaption);
	iAgendaStore.removeAll();
	refreshUI(false);
//	air.trace('session_id: '+aSessionID);
	sessions.each(function(record){
		if(record.get('session_id')==aSessionID){			
			//Ask for password?
			iSessionRecord = record;
			iToken = record.get('token') || aToken;
			if(iToken && iToken!=''){
				//Token defined. Check connection
				verifyToken();
			}else{
				//Ask for password
				iToken = null;
				askForPassword();
			}
			return false;
		}
	});
}

var recreateSessionsMenu = function(){
	for(var i = 2; i<iSessionMenu.items.getCount();){
		var lMenuItem = iSessionMenu.items.get(i);
		iSessionMenu.remove(lMenuItem);
	}
	sessions.each(function(record){
		var lMenuItem = new Ext.menu.Item({
			text: record.get('login')+'@'+record.get('server'),
			iconCls: 'session',
			handler: function(item){
				loadSession(item.sessionID);
			}
		});
		lMenuItem.sessionID = record.get('session_id');
		iSessionMenu.add(lMenuItem);
	});
}

var newSessionCreated = function(aServer, aLogin, aXML, aSavePassword){
	air.trace('noteID: '+aXML.getAttribute('rootNoteID'));
	var sessionID = sessions.addSession(aServer, aLogin, aSavePassword?aXML.getAttribute('token'):null,
			aXML.getAttribute('rootNoteID'), sessions.getCount()==0);
	recreateSessionsMenu();
	loadSession(sessionID, aXML.getAttribute('token'));
};

Ext.onReady(function(){
	Ext.QuickTips.init();
	
	iStatusBar = new Ext.StatusBar({
		defaultText: 'Idle',
		region: 'south'
	});
	
	iSessionMenu = new Ext.menu.Menu({
		items:[
			{
				text: 'New session...',
				iconCls: 'add_session',
				handler: function(){
					openNewSessionWindow();
				}
			},'-'
		]
	});
	
	iRefreshButton = new Ext.Toolbar.Button({
		iconCls: 'refresh',
//		text: 'Reload',
		tooltip: 'Reload agenda',
		handler: function(){
			refreshAgenda(true);
		}
	});
	
	iSessionButton = new Ext.Toolbar.Button({
//		text: 'Sessions',
		iconCls: 'sessions',
		tooltip: 'Change account',
		menu: iSessionMenu
	});
	
	iPasteButton = new Ext.Toolbar.Button({
		iconCls: 'paste',
//		text: 'Paste',
		tooltip: 'Paste from clipboard',
		handler: function(){
			doProcessClipboard();
		}
	});
	
	iSettingsButton = new Ext.Toolbar.Button({
//		text: 'Settings',
		tooltip: 'Modify settings',
		iconCls: 'settings',
		handler: function(){
			openNewWindow('settingsWin', 'settings.html');
		}
	});
	
	iMainToolbar = new Ext.Toolbar({
		items: [iSessionButton, ' ',iRefreshButton, iPasteButton, '-',iSettingsButton]
	});
	
	//Main grid
	
	iAgendaStore = new Ext.data.SimpleStore({
		fields: [
			{name: 'id'},
			{name: 'selectable'},
			{name: 'name'},
			{name: 'icon'},
			{name: 'crumb'},
			{name: 'add_icon'},
			{name: 'urgent'},
			{name: 'dates'},
			{name: 'recInfo'},
			{name: 'checked'}
		]
	});
	
	var iTaskNameRenderer = function(value, meta, record){
		var res = '';
		res += '<img src="im/types/p'+record.get('icon')+'.png" class="png_img"/>';
		if(record.get('add_icon'))
			res += '&nbsp;<img src="im/'+record.get('add_icon')+'" class="png_img"/>';
		res += '<span class="link_text">'+value+'</span>';
		if(record.get('dates')){
			res += '<div class="dates"><span class="urgent'+record.get('urgent')+' link_text" '+
					'style="padding-top: 3px; padding-left: 0px;">'+record.get('dates')+'</span></div>';			
		}
		if(record.get('crumb'))
			res += '<div class="crumb">'+record.get('crumb')+'</div>';
		return '<div>'+res+'</div>';	
	}
	
	var iTaskSelector = new Ext.grid.TaskSelectionModel({
		dataIndex: 'checked',
		singleSelect: true
	});
	
	iTagsToolbar = new Ext.Toolbar({
		items: [
			'Tags:'
		]
	});
	
	iAgendaGrid = new Ext.grid.GridPanel({
		store: iAgendaStore,
		border: false,
		region: 'center',
		tbar: iTagsToolbar,
		cm: new Ext.grid.ColumnModel([
			iTaskSelector,
			{id: 'first', header: 'Name', dataIndex: 'name', sortable: false, menuDisabled:true, renderer: iTaskNameRenderer}
		]),
		sm: iTaskSelector,
		viewConfig: {
            forceFit:true
        },
		autoExpandColumn: 'first'
	});
	
	//Main grid end
	
	var iMainWin = new Ext.air.NativeWindow({
		id: 'mainWindow',
		instance: window.nativeWindow,
		minimizeToTray: true,
		trayIcon: 'icons/AIRApp_16.png',
		trayTip: 'BeOrganzized! Desktop',
		trayMenu : [{
			text: 'Open BeOrganzized! Desktop',
			handler: function(){
				iMainWin.activate();
			}
		}, '-', {
			text: 'Exit',
			handler: function(){
				air.NativeApplication.nativeApplication.exit();
			}
		}]
	});
	
	iSaveButton = new Ext.Button({
		text: 'Save',
		handler: function(){
			var ids = '';
			iAgendaStore.each(function(record){
				if(record.get('checked')){
					if(ids!='')
						ids += ',';
					ids += record.get('id');
				}
			});
			if(ids=='')
				return;
			callAPI(iSessionRecord.get('server'), 'agenda.CompleteTasks', {
				noteids: ids,
				token: iToken
			}, function(aXML){
				showNotification('Tasks saved');
				refreshAgenda(false);
			});	
		}
	});
	
	iTaskField = new Ext.form.TextField({
		ctCls: 'x-table-layout',
		style: 'width: 100%;',
		emptyText: 'Enter task name and hit Enter',
		enableKeyEvents: true
	});
	
	iDDPanel = new Ext.Panel({
		html: '<div class="dd">DROP CONTENT HERE</div>',
		bodyStyle :'background-color: #f0f0f0;'
	});
	
	var lToolbar = new Ext.Toolbar({
		items: [iTaskField, {
			iconCls: 'help',
			tooltip: 'Read more about quick task syntax',
			handler: function(){
				air.navigateToURL(new air.URLRequest('http://dev.beorganized.org/features/quick-syntax/'));
			}
		}]
	});
	
	iEditorsPanel = new Ext.Panel({
		tbar:lToolbar,
		region: 'north',
		layout: 'fit',
		border: false,
		items: iDDPanel,
		height: 70
	});
	
	iEditorsPanel.hide();
	
	var panel = new Ext.Panel({
		region: 'center',
		layout: 'fit',
		items: [iAgendaGrid],
		buttonAlign: 'center',
		buttons: [iSaveButton]
	});
	
	viewport = new Ext.Viewport({
		layout: 'fit',
		items: {
			tbar: iMainToolbar,
			border: false,
			layout: 'border',
			items:[panel, iStatusBar, iEditorsPanel]
		}
    });

	iTagsToolbar.setVisible(false);
	iMainWin.on('closing', function(){
		Ext.air.NativeWindowManager.closeAll();
	});
	
	recreateSessionsMenu();
	refreshUI(false);
	sessions.each(function(record){
		if(record.get('load_at_start')){
			loadSession(record.get('session_id'));
			return false;
		}
	});
	
	iDDPanel.body.on('dragover', function(e){
		if(networkFlag>0)
			return;
		if(e.hasFormat(Ext.air.DragType.TEXT) || e.hasFormat(Ext.air.DragType.URL) || 
				e.hasFormat(Ext.air.DragType.FILES)){
			e.preventDefault();
		}
	});
	
	var makeNewElement = function(aType, aTypeName, aParams, aFile, aOkListener, aErrorListener){
		var lRnd = generateRandomString(15);
		var lParams = {
			id: iSessionRecord.get(aTypeName),
			type: aType,
//			name: item.getValue(),
//			quickadd: 'true',
			newNote: 'true',
			token: iToken,
			rnd: lRnd
		};
		
		for(var id in aParams){
			lParams[id] = aParams[id];
		}
		var lElementName = 'Note';
		if(aType==TYPE_TASK)
			lElementName = 'Task';
		if(aType==TYPE_FILE)
			lElementName = 'File';
		if(aType==TYPE_BMARK)
			lElementName = 'Bookmark';
			
		sendForm(iSessionRecord.get('server'), 'SaveNote', lParams, function(){
			air.trace('seems to be ok');
			callAPI(iSessionRecord.get('server'), 'CheckSaveResult', {
				rnd: lRnd,
				token: iToken
			}, function(){
				//Done
				showNotification(lElementName+' <i>'+escapeHTML(aParams.name)+'</i> has been added');
				if(aOkListener)
					aOkListener();
			}, function(){
				showNotification(lElementName+' <i>'+escapeHTML(aParams.name)+'</i> hasn\'t been added');
				if(aErrorListener)
					aErrorListener();				
			});
		}, function(){
			showError('Can\'t upload data to server. Please try again later');
//			air.trace('error???');
			showNotification(lElementName+' <i>'+escapeHTML(aParams.name)+'</i> hasn\'t been added');
			if(aErrorListener)
				aErrorListener();				
		}, aFile)
	}
	
	var saveURL = function(aURL){
		if(aURL.indexOf('\n')!=-1){
			aURL = aURL.substring(0, aURL.indexOf('\n'));
		}
		air.trace('Loading URL: ['+aURL+']');
		var lTitle = aURL;
		callURL(aURL, function(aData){
			if(aData){
				var lRegexp = new RegExp("<TITLE>.+</TITLE>", "i");
				var title = lRegexp.exec(aData);
				if(title){
					air.trace('title: '+title[0]+', length = '+title[0].length);
					lTitle = title[0].substring(7, title[0].length-8);
				}
			}
			air.trace('lTitle: '+lTitle);
			makeNewElement(TYPE_BMARK, 'bookmarks_id', {
				name: lTitle,
				url: aURL
			});
		});
		return true;
	}
	
	var saveText = function(aText){
		var MAX_TITLE_SIZE = 40;
		if(!aText)
			return false;
		aText = aText.trim();
		if(''==aText)
			return false;
		var lTitle = '';
//		while(aText.startsWith('\n'))
		if(aText.indexOf('\n')!=-1){
			lTitle = aText.substring(0, aText.indexOf('\n')-1);
			if(lTitle.length>MAX_TITLE_SIZE)
				lTitle = lTitle.substring(0, MAX_TITLE_SIZE).trim()+'...';
		}else{
			if(aText.length>MAX_TITLE_SIZE)
				lTitle = aText.substring(0, MAX_TITLE_SIZE).trim()+'...';
			else
				lTitle = aText;
		}
		air.trace('Text title: ['+lTitle+']');
		makeNewElement(TYPE_TEXT, 'notes_id', {
			name: lTitle,
			textContent: aText
		});
		return true;
	}
	
	iTaskField.on('keydown', function(item, event){
		if(event.getKey()==Ext.EventObject.ENTER && item.getValue()){
			makeNewElement(TYPE_TASK, 'tasks_id', {
				name: item.getValue(),
				quickadd: 'true'
			}, null, function(){
				iTaskField.setValue('');
				iTaskField.focus(false, 10);				
			}, function(){
				iTaskField.focus(false, 10);				
			});
		}
	});
	
	var processExternalData = function(e){
		air.trace('something dropped: '+e);
		if(e.hasFormat(Ext.air.DragType.URL)){
			//Work with URL
			var lText = e.getData(Ext.air.DragType.URL);
//			air.trace('URL: '+lText);
			saveURL(lText);
			return;
		}
		if(e.hasFormat(Ext.air.DragType.FILES)){
			//Work with FILES
			var lFiles = e.getData(Ext.air.DragType.FILES);
			for(var i = 0; i<lFiles.length; i++){
				var lFile = lFiles[i];
				if(lFile.isDirectory)
					continue;
				
				air.trace('Sending file: '+lFile.name);
				makeNewElement(TYPE_FILE, 'notes_id', {
					name: lFile.name
				}, lFile);
				
			}
			return;
		}
		if(e.hasFormat(Ext.air.DragType.TEXT)){
			//Work with text
			var lText = e.getData(Ext.air.DragType.TEXT);
			air.trace('Text: '+lText);
			saveText(lText);
		}		
	}
	
	iDDPanel.body.on('drop', function(e){
		processExternalData(e);
	});
		
	var doProcessClipboard = function(){
		var e = air.Clipboard.generalClipboard;
		if (e.hasFormat(air.ClipboardFormats.TEXT_FORMAT) || e.hasFormat(air.ClipboardFormats.URL_FORMAT) ||
				e.hasFormat(air.ClipboardFormats.FILE_LIST_FORMAT)) {
			if(e.hasFormat(air.ClipboardFormats.URL_FORMAT)){
				//Work with URL
				var lText = e.getData(air.ClipboardFormats.URL_FORMAT);
	//			air.trace('URL: '+lText);
				if(saveURL(lText))
					e.clear();
				return;
			}
			if(e.hasFormat(air.ClipboardFormats.FILE_LIST_FORMAT)){
				//Work with FILES
				var lFiles = e.getData(air.ClipboardFormats.FILE_LIST_FORMAT);
				for(var i = 0; i<lFiles.length; i++){
					var lFile = lFiles[i];
					if(lFile.isDirectory)
						continue;
					air.trace('Sending file: '+lFile.name);
					makeNewElement(TYPE_FILE, 'notes_id', {
						name: lFile.name
					}, lFile);
				}
				e.clear();
				return;
			}
			if(e.hasFormat(air.ClipboardFormats.TEXT_FORMAT)){
				//Work with text
				var lText = e.getData(air.ClipboardFormats.TEXT_FORMAT);
				air.trace('Text: '+lText);
				if(saveText(lText)){
					e.clear();
				}
			}		
			
		}
	};
	
	if(sessions.getCount()==0)
		openNewSessionWindow();
	iMainWin.show();
	iMainWin.instance.activate();
	
});
